package kr.pe.johnkim.app.mobile.rest.controller;

import kr.pe.johnkim.app.domain.MyHistoryCategory;
import kr.pe.johnkim.app.domain.MyHistoryItem;
import kr.pe.johnkim.app.mobile.rest.service.MyHistoryCategoryService;
import kr.pe.johnkim.app.mobile.rest.service.MyHistoryItemService;
import kr.pe.johnkim.app.mobile.util.MyHistoryCommon;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author : johnkim <cale9797@gmail.com / Bettersoft Inc,.>
 * @Date : 12. 2. 1
 */

@Controller
@Path("/myHistoryCategoryController")
public class MyHistoryCategoryController {
    // SLF4J Logging
	private Logger logger = LoggerFactory.getLogger(MyHistoryCategoryController.class);

    @Autowired
    private MyHistoryCategoryService myHistoryCategoryService = null;

    @Autowired
    private MyHistoryItemService myHistoryItemService = null;

    @Autowired
    private MyHistoryCommon myHistoryCommon = null;

    /**
     * 카테고리 중복을 확인 한다.
     *
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/checkDuplication")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory checkDuplication(InputStream is) throws IOException, JSONException {
        logger.info("checkDuplication");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonDuplication = new JSONObject(line);
        JSONObject jsonDuplication2 = jsonDuplication.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setName(jsonDuplication2.getString("name"));
        parameterCategory.setActivateYn(jsonDuplication2.getString("activateYn"));
        parameterCategory.setMyHistoryMembersId(jsonDuplication2.getString("myHistoryMembersId"));
//        parameterCategory.setMyHistoryGroupsIdMyHistoryGroups(jsonDuplication2.getString("myHistoryGroupsIdMyHistoryGroups"));

        logger.info("name                             : {}", parameterCategory.getName());
        logger.info("activateYn                       : {}", parameterCategory.getActivateYn());
        logger.info("myHistoryMembersId               : {}", parameterCategory.getMyHistoryMembersId());
//        logger.info("myHistoryGroupsIdMyHistoryGroups : {}", parameterCategory.getMyHistoryGroupsIdMyHistoryGroups());

        return myHistoryCategoryService.checkDuplication(parameterCategory);
    }

    /**
     * Category 목록을 가져 온다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/selectCategoryList")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public List<MyHistoryCategory> selectCategoryList(InputStream is) throws IOException, JSONException {
        logger.info("selectCategoryList");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));
        parameterCategory.setCategoryStart(Integer.parseInt(jsonCategory2.getString("categoryStart")));
        parameterCategory.setCategoryCount(Integer.parseInt(jsonCategory2.getString("categoryCount")));

        logger.info("myHistoryMembersId : {}", parameterCategory.getMyHistoryMembersId());
        logger.info("activateYn         : {}", parameterCategory.getActivateYn());
        logger.info("categoryStart      : {}", parameterCategory.getCategoryStart());
        logger.info("categoryCount      : {}", parameterCategory.getCategoryCount());

        return myHistoryCategoryService.selectCategoryList(parameterCategory);
    }

    /**
     * 선택한 카테고리의 상세 정보를 가져 온다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/selectCategory")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory selectCategory(InputStream is) throws IOException, JSONException {
        logger.info("selectCategory");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setIdMyHistoryCategories(jsonCategory2.getString("idMyHistoryCategories"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));

        logger.info("idMyHistoryCategories : {}", parameterCategory.getIdMyHistoryCategories());
        logger.info("activateYn            : {}", parameterCategory.getActivateYn());

        return myHistoryCategoryService.selectCategory(parameterCategory);
    }

    /**
     * Category Analysis 화면에 출력 하기 위한 item 목록을 가져 온다.
     *
     * item 의 갯수는 넘겨 받은 client 에서 list 의 size 로 계산 한다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/selectItemListForCategoryAnalysis")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public List<MyHistoryItem> selectItemListForCategoryAnalysis(InputStream is) throws IOException, JSONException {
        logger.info("selectItemListForCategoryAnalysis");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonItem = new JSONObject(line);
        JSONObject jsonItem2 = jsonItem.getJSONObject("myHistoryItem");

        MyHistoryItem parameterItem = new MyHistoryItem();

        parameterItem.setActivateYn(jsonItem2.getString("activateYn"));
        parameterItem.setMyHistoryMembersId(jsonItem2.getString("myHistoryMembersId"));
//        parameterItem.setMyHistoryCategoriesIdMyHistoryCategories(jsonItem2.getString("myHistoryCategoriesIdMyHistoryCategories"));

        logger.info("activateYn                               : {}", parameterItem.getActivateYn());
        logger.info("myHistoryMembersId                       : {}", parameterItem.getMyHistoryMembersId());
//        logger.info("myHistoryCategoriesIdMyHistoryCategories : {}", parameterItem.getMyHistoryCategoriesIdMyHistoryCategories());

        return myHistoryCategoryService.selectItemListForCategoryAnalysis(parameterItem);
    }

    /**
     * Category 를 등록 한다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/registerCategory")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory registerCategory(InputStream is) throws IOException, JSONException {
        logger.info("registerCategory");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setName(jsonCategory2.getString("name"));
        parameterCategory.setComment(jsonCategory2.getString("comment"));
        parameterCategory.setIconUrl(jsonCategory2.getString("iconUrl"));
        parameterCategory.setOpenCategoryYn(jsonCategory2.getString("openCategoryYn"));
        parameterCategory.setFavoriteYn(jsonCategory2.getString("favoriteYn"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));
        parameterCategory.setModifyDate(jsonCategory2.getString("modifyDate"));
        parameterCategory.setRegisterDate(jsonCategory2.getString("registerDate"));
        parameterCategory.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));

        logger.info("name                             : {}", parameterCategory.getName());
        logger.info("comment                          : {}", parameterCategory.getComment());
        logger.info("openCategoryYn                   : {}", parameterCategory.getOpenCategoryYn());
        logger.info("favoriteYn                       : {}", parameterCategory.getFavoriteYn());
        logger.info("activateYn                       : {}", parameterCategory.getActivateYn());
        logger.info("modifyDate                       : {}", parameterCategory.getModifyDate());
        logger.info("registerDate                     : {}", parameterCategory.getRegisterDate());
        logger.info("myHistoryMembersId               : {}", parameterCategory.getMyHistoryMembersId());

        MyHistoryCategory resultCategory = new MyHistoryCategory();

        if(myHistoryCategoryService.registerCategory(parameterCategory)) {
            resultCategory.setResult("SUCCESS");
        } else {
            resultCategory.setResult("FAIL");
        }

        return resultCategory;
    }

    /**
     * 카테고리 내용을 수정 한다.
     *
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/updateCategory")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory updateCategory(InputStream is) throws IOException, JSONException {
        logger.info("updateCategory");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setIdMyHistoryCategories(jsonCategory2.getString("idMyHistoryCategories"));
        parameterCategory.setName(jsonCategory2.getString("name"));
        parameterCategory.setComment(jsonCategory2.getString("comment"));
        parameterCategory.setIconUrl(jsonCategory2.getString("iconUrl"));
        parameterCategory.setOpenCategoryYn(jsonCategory2.getString("openCategoryYn"));
        parameterCategory.setFavoriteYn(jsonCategory2.getString("favoriteYn"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));
        parameterCategory.setModifyDate(jsonCategory2.getString("modifyDate"));
        parameterCategory.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));

        logger.info("idMyHistoryCategories            : {}", parameterCategory.getIdMyHistoryCategories());
        logger.info("name                             : {}", parameterCategory.getName());
        logger.info("comment                          : {}", parameterCategory.getComment());
        logger.info("openCategoryYn                   : {}", parameterCategory.getOpenCategoryYn());
        logger.info("favoriteYn                       : {}", parameterCategory.getFavoriteYn());
        logger.info("activateYn                       : {}", parameterCategory.getActivateYn());
        logger.info("modifyDate                       : {}", parameterCategory.getModifyDate());
        logger.info("myHistoryMembersId               : {}", parameterCategory.getMyHistoryMembersId());

        MyHistoryCategory resultCategory = new MyHistoryCategory();

        if(myHistoryCategoryService.updateCategory(parameterCategory)) {
            resultCategory.setResult("SUCCESS");
        } else {
            resultCategory.setResult("FAIL");
        }

        return resultCategory;
    }

    /**
     * 사용자가 선택한 카테고리를 비활성화 한다.
     *
     * 실행 결과를 SUCCESS or FAIL 의 string 으로 MyHistoryCategory 도메인 클래스에 담아서 반환 한다.
     *
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/updateDeactivateCategory")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory updateDeactivateCategory(InputStream is) throws IOException, JSONException {
        logger.info("updateDeactivateCategory");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setIdMyHistoryCategories(jsonCategory2.getString("idMyHistoryCategories"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));
        parameterCategory.setModifyDate(jsonCategory2.getString("modifyDate"));
        parameterCategory.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));

        MyHistoryCategory resultCategory = new MyHistoryCategory();

        if(myHistoryCategoryService.updateDeactivateCategory(parameterCategory)) {
            resultCategory.setResult("SUCCESS");
        } else {
            resultCategory.setResult("FAIL");
        }

        /**
         * Category 를 비 활성화 한 다음 해당 Category 에 해당 하는 item 목록을 비 활성화 한다.
         */
        MyHistoryItem parameterItem = new MyHistoryItem();

        parameterItem.setActivateYn("Y");
        parameterItem.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));
        parameterItem.setMyHistoryCategoriesIdMyHistoryCategories(jsonCategory2.getString("idMyHistoryCategories"));

        List<MyHistoryItem> parameterItemList = myHistoryItemService.selectItemListForCategory(parameterItem);

        for(int i=0 ; i<parameterItemList.size() ; i++) {
            MyHistoryItem mMyHistoryItem = new MyHistoryItem();

            mMyHistoryItem.setIdMyHistoryItems(parameterItemList.get(i).getIdMyHistoryItems());
//            mMyHistoryItem.setName(parameterItemList.get(i).getName());
//            mMyHistoryItem.setComment(parameterItemList.get(i).getComment());
//            mMyHistoryItem.setAmount(parameterItemList.get(i).getAmount());
//            mMyHistoryItem.setOpenItemYn(parameterItemList.get(i).getOpenItemYn());
//            mMyHistoryItem.setFavoriteYn(parameterItemList.get(i).getFavoriteYn());
            mMyHistoryItem.setActivateYn(jsonCategory2.getString("activateYn"));
            mMyHistoryItem.setModifyDate(jsonCategory2.getString("modifyDate"));
            mMyHistoryItem.setMyHistoryMembersId(parameterItemList.get(i).getMyHistoryMembersId());
//            mMyHistoryItem.setMyHistoryCategoriesIdMyHistoryCategories(parameterItemList.get(i).getMyHistoryMembersId());

            myHistoryItemService.updateDeactivateItem(mMyHistoryItem);
        }

        return resultCategory;
    }

    /**
     * Category 를 즐겨 찾기에 등록 한다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/updateFavoriteCategory")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory updateFavoriteCategory(InputStream is) throws IOException, JSONException {
        logger.info("updateFavoriteCategory");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setIdMyHistoryCategories(jsonCategory2.getString("idMyHistoryCategories"));
        parameterCategory.setFavoriteYn(jsonCategory2.getString("favoriteYn"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));
        parameterCategory.setModifyDate(jsonCategory2.getString("modifyDate"));
        parameterCategory.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));

        MyHistoryCategory resultCategory = new MyHistoryCategory();

        if(myHistoryCategoryService.updateFavoriteCategory(parameterCategory)) {
            resultCategory.setResult("SUCCESS");
        } else {
            resultCategory.setResult("FAIL");
        }

        return resultCategory;
    }

    /**
     * Category 를 즐겨 찾기에서 등록 해제 한다.
     * 
     * @param is
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @POST
    @Path("/updateDeactivateFavoriteCategory")
    @Consumes({"application/json", "application/xml"})
    @Produces({"application/json", "application/xml"})
    public MyHistoryCategory updateDeactivateFavoriteCategory(InputStream is) throws IOException, JSONException {
        logger.info("updateDeactivateFavoriteCategory");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();

        logger.info("line : {}", line);

        JSONObject jsonCategory = new JSONObject(line);
        JSONObject jsonCategory2 = jsonCategory.getJSONObject("myHistoryCategory");

        MyHistoryCategory parameterCategory = new MyHistoryCategory();

        parameterCategory.setIdMyHistoryCategories(jsonCategory2.getString("idMyHistoryCategories"));
        parameterCategory.setFavoriteYn(jsonCategory2.getString("favoriteYn"));
        parameterCategory.setActivateYn(jsonCategory2.getString("activateYn"));
        parameterCategory.setModifyDate(jsonCategory2.getString("modifyDate"));
        parameterCategory.setMyHistoryMembersId(jsonCategory2.getString("myHistoryMembersId"));

        MyHistoryCategory resultCategory = new MyHistoryCategory();

        if(myHistoryCategoryService.updateDeactivateFavoriteCategory(parameterCategory)) {
            resultCategory.setResult("SUCCESS");
        } else {
            resultCategory.setResult("FAIL");
        }

        return resultCategory;
    }
}
